package com.ztftrue.ble;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aprilbrother.aprilbrothersdk.Beacon;
import com.aprilbrother.aprilbrothersdk.BeaconManager;
import com.aprilbrother.aprilbrothersdk.Region;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class MainActivity extends Activity {
    private Region ALL_BEACONS_REGION;
    private BeaconManager beaconManager;
    private android.widget.TextView textView;
    private android.widget.EditText majorE;
    private android.widget.EditText minorE;
    private android.widget.EditText uuidE;
    private android.widget.EditText distanceE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        uuid = intent.getStringExtra("uuid");
        major = intent.getIntExtra("major", 0);
        minor = intent.getIntExtra("minor", 0);
        setContentView(R.layout.activity_main);
        this.distanceE = (EditText) findViewById(R.id.distanceE);
        this.uuidE = (EditText) findViewById(R.id.uuidE);
        this.minorE = (EditText) findViewById(R.id.minorE);
        this.majorE = (EditText) findViewById(R.id.majorE);
        this.textView = (TextView) findViewById(R.id.textView);
        changeText();
    }

    private void changeText() {
        if (major == 0) {
            ALL_BEACONS_REGION = new Region("customRegionName", uuid, null, minor);
        } else if (minor == 0) {
            ALL_BEACONS_REGION = new Region("customRegionName", uuid, major, null);
        } else {
            ALL_BEACONS_REGION = new Region("customRegionName", uuid, major, minor);
        }
        if (uuid != null) {
            uuidE.setText(uuid);
        }
        minorE.setText(String.valueOf(minor));
        majorE.setText(String.valueOf(major));
        startBlueTooth();
    }

    String uuid;
    int major;
    int minor;
    double distCompare = 0;
    double distance;

    private void startBlueTooth() {
        beaconManager = new BeaconManager(getApplicationContext());
        beaconManager.setForegroundScanPeriod(2000, 1000);//2000次，1000毫秒等待
        beaconManager.setRangingListener(new BeaconManager.RangingListener() {
            @Override
            public void onBeaconsDiscovered(Region region,
                                            final List<Beacon> beacons) {
                if (beacons != null && beacons.size() > 0) {
                    for (Beacon data : beacons) {
                        distance = Math.pow(10, (Math.abs(data.getRssi()) - 80.0F) / (10 * 2));
                        if (minor == 0) {
                            minor = data.getMinor();
                        }
                        if (major == 0) {
                            major = data.getMajor();
                        }
                        if (uuid.toUpperCase().equals(data.getProximityUUID().toUpperCase())
                                && minor == data.getMinor()
                                && major == data.getMajor()
                                ) {
                            if (distCompare < distance) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        textView.setText(String.valueOf(distance));

                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        textView.setText("超出距离");
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textView.setText("没有相关蓝牙");
                                }
                            });
                        }
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText("没有任何蓝牙");
                        }
                    });
                }
            }
        });


        beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() {

            @Override
            public void onExitedRegion(Region region) {
                Toast.makeText(MainActivity.this, "Notify in", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onEnteredRegion(Region region, List<Beacon> beacons) {
                Toast.makeText(MainActivity.this, "Notify out", Toast.LENGTH_LONG).show();
            }
        });
        beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
            @Override
            public void onServiceReady() {
                try {
                    beaconManager.startRanging(ALL_BEACONS_REGION);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ALL_BEACONS_REGION != null) {
            try {
                beaconManager.stopRanging(ALL_BEACONS_REGION);
                beaconManager.stopMonitoring(ALL_BEACONS_REGION);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void stop() {
        if (ALL_BEACONS_REGION != null && beaconManager != null) {
            try {
                beaconManager.stopRanging(ALL_BEACONS_REGION);
                beaconManager.stopMonitoring(ALL_BEACONS_REGION);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(MainActivity.this, "刷新出错", Toast.LENGTH_LONG).show();
        }
    }

    public void change(View view) {
        stop();
        uuid = uuidE.getText().toString();
        minor = Integer.parseInt(minorE.getText().toString());
        major = Integer.parseInt(majorE.getText().toString());
        distCompare = Double.parseDouble(distanceE.getText().toString());
        changeText();
    }

    public void save(View view) {
       /* {
            "uuid":"4adbe522-80a6-402f-b64a-68575b046671",
                "major":"10000",
                "minor":"5000",
                "exhibit_id":"szjybwg_zx1_htl",
                "exhibit_name":"汉推楼（体验馆）"
        },*/
        String content = "{uuid:\"" + uuid + "\",\"major\":\"" + major + "\",\"minor\":\"" + minor + "\",\"distance\":\"" + distance + "\",\"compare\":\"" + distCompare + "\"},";
        try {
            /* 根据用户提供的文件名，以及文件的应用模式，打开一个输出流.文件不存系统会为你创建一个的，
             * 至于为什么这个地方还有FileNotFoundException抛出，我也比较纳闷。在Context中是这样定义的
             *   public abstract FileOutputStream openFileOutput(String name, int mode)
             *   throws FileNotFoundException;
             * openFileOutput(String name, int mode);
             * 第一个参数，代表文件名称，注意这里的文件名称不能包括任何的/或者/这种分隔符，只能是文件名
             *          该文件会被保存在/data/data/应用名称/files/chenzheng_java.txt
             * 第二个参数，代表文件的操作模式
             *             MODE_PRIVATE 私有（只能创建它的应用访问） 重复写入时会文件覆盖
             *             MODE_APPEND  私有   重复写入时会在文件的末尾进行追加，而不是覆盖掉原来的文件
             *             MODE_WORLD_READABLE 公用  可读
             *             MODE_WORLD_WRITEABLE 公用 可读写
             *  */
            File file = new File(Environment.getExternalStorageDirectory() + "/bluetooth.txt");
            BufferedWriter outputStream = new BufferedWriter(new FileWriter(file, true));

            outputStream.write(content);
            outputStream.flush();
            outputStream.close();
            Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
